<template>
    <el-main v-loading="loading">
        <el-row :gutter="20" class="margin_bottom_30">
            <el-col :span="4">
                <el-input placeholder="输入勋章名称" size="small" v-model="filterData.medalName"></el-input>
            </el-col>
            <el-col :span="4">
                <el-select
                    v-model="filterData.medalType"
                    prop="campaignState"
                    placeholder="请选择勋章类型"
                    size="small"
                    style="width:100%"
                    @change="checkMedalType">
                    <el-option
                        v-for="item in medalTypeList"
                        :key="item.labelId"
                        :label="item.labelText"
                        :value="item.labelId"></el-option>
                </el-select>
            </el-col>
            <el-col :span="4" :offset="1">
                <p style="display: flex">
                    <el-button type="primary" size="small" @click="search">搜 索</el-button>
                    <el-button size="small" @click="resetQuery">重 置</el-button>
                    <el-button type="primary" size="small" @click="handleActionPage">新增勋章</el-button>
                </p>
            </el-col>
        </el-row>
        <el-table
            :data="dataList"
            border
            :row-key="row => row.medalUid"
            height="640"
            :header-cell-style="{background:'#afafaf',color:'#606266'}"
            ref="multipleTable"
            @selection-change="handleSelectionChange"
        >
            <el-table-column type="selection" align="center" reserve-selection width="40"></el-table-column>
            <el-table-column prop="medalName" align="center" width="150" label="勋章名称"></el-table-column>
            <el-table-column align="center" width="100" label="勋章类型">
                 <template slot-scope="scope">
                    <p>{{getMedalTypeStatus(scope.row.medalType)}}</p>
                </template>
            </el-table-column>
            <el-table-column align="center" width="100" label="勋章图(亮)">
                <template slot-scope="scope">
                     <el-tooltip content="勋章点亮图标">
                        <img v-image-preview :src="scope.row.medalImageUrlOn" width="60" />
                     </el-tooltip>
			    </template>
            </el-table-column>
            <el-table-column align="center" width="100" label="勋章图(暗)">
                <template slot-scope="scope">
                    <el-tooltip content="勋章未点亮图标">
                        <img v-image-preview :src="scope.row.medalImageUrlOff" width="60" />
                     </el-tooltip>
			    </template>
            </el-table-column>
            <el-table-column prop="createTime" align="center" width="160" label="创建时间"></el-table-column>
            <el-table-column align="center" min-width="300" label="描述">
                <template slot-scope="scope">
                    <el-tooltip :content="scope.row.medalDesc">
                        <p>{{scope.row.medalDesc}}</p>
                    </el-tooltip>
                </template>
            </el-table-column>
            <el-table-column width="150" label="获得规则" align="center">
                <template slot-scope="scope">
                    <p><span>{{scope.row.medalGetText}}</span></p>
                </template>
            </el-table-column>
            <el-table-column align="center" width="100" label="勋章海报">
                <template slot-scope="scope">
                    <el-tooltip content="勋章分享海报">
                        <img v-image-preview :src="scope.row.medalPosterImageUrl" width="60" />
                     </el-tooltip>
			    </template>
            </el-table-column>
            <el-table-column align="center" width="200" label="勋章权益">
                <template slot-scope="scope">
                     <el-tooltip :content="item.medalEquityName" v-for="(item, index) of scope.row.rightItems" :key="index">
                        <div class="rightItems">
                            <img class="rightItems_icon" v-image-preview v-if="item.medalEquityImage" :src="item.medalEquityImage" />
                            <p class="rightItems_name">{{item.medalEquityName | controlLength}}</p>
                        </div>
                    </el-tooltip>
                    <p class="text_align_left">
                        <el-button
                            type="text"
                            @click="handleEquity(scope.row)"
                            :disabled="!scope.row.medalType"
                            size="small">
                        配置权益</el-button>
                    </p>
                </template>
            </el-table-column>
            <el-table-column prop="memberGetCount" align="center" width="100" label="获取次数"></el-table-column>
            <el-table-column prop="status" align="center" width="100" label="状态">
                <template slot-scope="scope">
                    <span>{{!scope.row.medalStatus ? '已启用' : '未启用'}}</span>
                </template>
            </el-table-column>
            <el-table-column fixed="right" align="center" label="操作" width="200">
                <template slot-scope="scope">
                    <el-button type="text" @click="handleEdit(scope.row)" size="small">编辑</el-button>
                    <el-button type="text" @click="handleDel(scope.row)" size="small">删除</el-button>
                    <el-button type="text" @click="handleUpdate(scope.row)" size="small">
                        {{!scope.row.medalStatus ? '停用' : '启用'}}
                    </el-button>
                </template>
            </el-table-column>
        </el-table>

        <div class="footer flex-between">
             <el-checkbox v-model="checkAll" :disabled="!dataList.length" @change="handleCheckAllChange">
                全选
            </el-checkbox>
            <el-pagination
                @current-change="handleCurrentChange"
                :current-page="page"
                :page-size="10"
                background
                :disabled="!dataList.length"
                :total="count"
                layout="total, prev, pager, next, jumper">
            </el-pagination>
        </div>
      
		<el-dialog
            :title="!medalInfo.productUid ? '新增勋章' : '编辑勋章'"
            @close="handleCloseAction"
            :visible.sync="showActionPage"
            destroy-on-close
            :modal-append-to-body="false"
            :close-on-click-modal="false"
            width="40%">
			<medal-action
                ref="medalRef"
                :infoData="medalInfo"
                :rulesList="rulesList"
                :medalDataList="dataList"
                :medalEquityList="medalEquityList"
                @func="closeTemplatePage"
                :medalTypeList="medalTypeList"></medal-action>
		</el-dialog>

        <medal-equity :info="medalInfo" v-if="showMedalEquity" :medalEquityList="medalEquityList" />
    </el-main>
</template>
<script>
    import medalAction from './medal/action/index.vue';
    import medalEquity from './medal/action/medal-equity.vue';
    import utils from '@/utils/utils';
    import {
        medalList,
        rightsList,
        deleteMedal,
        setEquity,
        updateMedalState
	} from "@/api/table";

    export default {
        name: "MEDAL_LIST",
        filters: {
            controlLength: curStr => utils.controlLength(curStr, 18),
        },
        components: {
            medalAction,
            medalEquity
        },
        data() {
            return {
                count: 0,
                checkAll: false, // 全选
                medalTypeList: [{
					labelId: 1,
					labelText: '成就勋章'
				}, {
					labelId: 2,
					labelText: '特殊勋章'
				}],
                dataList: [],
                loading: true,
                page: 1,
                showMedalEquity: false,
                showActionPage: false,
                medalInfo: {},
                filterData: {},
                medalEquityList: [],
                rulesList: [
                //     {
				// 	labelId: 1,
				// 	labelText: '点赞'
                // }, 
                {
					labelId: 1,
					labelText: '送祝福'
				}, {
					labelId: 2,
					labelText: '收祝福'
				}, {
					labelId: 3,
					labelText: '评论'
				}, {
					labelId: 4,
					labelText: '分享'
				}, {
					labelId: 5,
					labelText: '收藏'
				}, {
					labelId: 6,
					labelText: '收集勋章'
				}],
            }
        },
        
        mounted() {
            Promise.all([
                this.getData(),
                this.getMedalEquityList()
            ]);
            this.$event.on('MedalEquityChange', data => {
                this.showMedalEquity = false;
                this.handleCloseAction();
                this.getData();
            });
            this.$event.on('CloseEquityPage', () => {
                this.showMedalEquity = false;
                this.handleCloseAction()
            });
        },
        destroyed() {
            this.$event.off('RelatedProducts');
            this.$event.off('CloseRelatedProducts')
            this.$event.off('MedalRluesChange')
            this.$event.off('CloseRluesPage')
        },
        methods: {
            // 权益列表
            getMedalEquityList() {
                rightsList({
                    page: 0,
                    size: 50
                }).then(res => {
                    if (res.data.isSuccessful === "Y") {
  
                        this.medalEquityList  = res.data.data.rights;
                    }
                });
            },
            // 获取类型
            getMedalTypeStatus(medalType) {
                const info = this.medalTypeList.find(item => item.labelId === medalType) || {}
                return info.labelText || ''
            },
            // 搜索
            search() {
                this.getData();
            },
            // 加载分页数据
            handleCurrentChange(val) {
                this.page = val;
                this.getData();
            },
            // 全选
            handleCheckAllChange(val) {
                if (this.checkAll) {
                    this.$refs.multipleTable.toggleAllSelection();
                } else {
                    this.$refs.multipleTable.clearSelection();
                }
            },
            resetQuery() {
                this.filterData = {};
                this.page = 1;
                this.getData();
            },

            handleCloseAction() {
                this.medalInfo = {}
            },
            // 勋章分类
            checkMedalType(e) {
                this.filterData.medalType = e;
                this.getData()
            },
            // 选择品牌
            checkBrand(e) {
                this.filterData.brandUid = e
            },
            handleActionPage() {
                this.showActionPage = true;
            },
            closeTemplatePage(data) {
                this.handleCloseAction()
                this.showActionPage = data.action;
                data.refresh && this.getData();
            },
            // 监听选择的内容
            handleSelectionChange(val) {
                // console.log(val)
                this.checkAll = this.dataList.length === val.length
            },
            // 获取数据
            getData() {
                medalList({
                    ...this.filterData,
                    page: this.page - 1
                }).then(res => {
                    if (res.data.isSuccessful === "Y") {
                        const { count, medalList } = res.data.data;
                        this.count = count;
                        this.dataList  = medalList;
                    }
                })
                .catch(err => {})
                .finally(() => {
                    if (this.loading) {
                        this.loading = false
                    }
                });
            },
            // 编辑
            handleEdit(info) {
                this.medalInfo = info;
                this.handleActionPage();
                // 同步数据
				this.$nextTick(() => {
					this.$refs.medalRef.updateData()
				})
            },

            // 设置权益
            handleEquity(info) {
                this.medalInfo = info;
                this.showMedalEquity = true;
            },
            // 更改状态
            handleUpdate(info) {
                this.$confirm( `是否${info.medalStatus ? '启用' : '停用'}该勋章?`, "提示", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning"
                }).then(() => {
                     let medalStatus = info.medalStatus ? 0 : 1;
					updateMedalState({
                        medalUid: info.medalUid,
                        medalStatus
                    }).then(res => {
                        if(res.data.isSuccessful !== "Y"){
                            this.$message.error(res.data.message);
                            return
                        }

                        this.$message.success(res.data.message);
                        setTimeout(() => {
                            this.getData();
                        }, 500)
                    }).catch(err => {});
				}).catch();
            },
            // 删除
            handleDel(info) {
                this.$confirm("是否删除该勋章?", "提示", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning"
                }).then(() => {
					deleteMedal({
                        medalUid: info.medalUid,
                    }).then(result => {
                        if(result.data.isSuccessful !== "Y"){
                            this.$message.error(result.data.message);
                            return
                        }

                        this.$message.success('成功删除！');
                        this.dataList = this.dataList.filter(item => item.medalUid  !== info.medalUid);
                        setTimeout(() => {
                            this.getData();
                        }, 500)
                    }).catch(err => {});
				}).catch();
            },
        }
    }
</script>
<style lang="scss" scoped>
    .rightItems {
        display: flex;
        align-content: center;
        margin-bottom: 10px;
        &_name {
            margin-left: 10px;
            text-align: left;
            font-size: 12px;
            line-height: 1.8;
        }
        &_icon {
            height: 40px;
            width: 40px;
            border-radius: 5px;
            object-fit: cover;
        }
    }
</style>
